package com.juyu.miliao.api.service;

import com.juyu.miliao.api.constant.EnergyLevelType;
import com.juyu.miliao.api.dao.mysql.BillDetailDao;
import com.juyu.miliao.api.dao.mysql.UserInfoDao;
import com.juyu.miliao.api.dao.mysql.UserWalletDao;
import com.juyu.miliao.api.dao.redis.UserRedisDao;
import com.juyu.miliao.api.domain.*;
import com.juyu.miliao.api.handler.UserInvitationIncomeDetailsHandler;
import com.juyu.miliao.api.util.SystemMessageUtil;
import com.juyu.miliao.common.constant.EnumType;
import com.juyu.miliao.common.exception.IllegalParamException;
import com.juyu.miliao.common.util.DoubleFormatUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Optional;

@Service
public class UserWalletService {
	@Resource
	private UserWalletDao userWalletDao;
	@Resource
	private CoinPriceService coinPriceService;
	@Resource
	private BillDetailDao billDetailDao;
	@Resource
	private SystemMessageUtil systemMessageUtil;
	@Resource
	private VestRobotMessageService vestRobotMessageService;
	@Resource
    private EnergyLevelService energyLevelService;
	@Resource
	private VipService vipService;
	@Resource
	private UserRedisDao userRedisDao;
	@Resource
	private UserInfoDao userInfoDao;

	@Resource
	private UserInvitationIncomeDetailsHandler userInvitationIncomeDetailsHandler;

	private final Logger logger = LoggerFactory.getLogger(UserWalletService.class);

	public UserWallet getUserWalletById(long userId) {
		UserWallet userWallet = userWalletDao.getUserWalletById(userId);
		double money = DoubleFormatUtil.doubleFormate(userWallet.getDiamond() / 100);
		userWallet.setMoney(money+"");
		return userWallet;
	}
	/**
	 * 购买金币，应该在支付异步通知接口时调用方法
	 * @param
	 */
	public void changeUserWallet(long userId, int contentId) {
		logger.info("保存金币充值记录：userId={},contentId={}",userId,contentId);
		//保存交易详细记录
//		BillDetail billDetail = new BillDetail();
//		billDetail.setRecordType(7);
//		billDetail.setInUserId(userId);
//		billDetail.setOutUserId(0);
		CoinPrice coinPrice = coinPriceService.getCoinPriceById(contentId);
//		billDetail.setSpend(coinPrice.getCoinNumber());
//		billDetailDao.insertBillDetail(billDetail);
		BillDetailDeposit billDetailDeposit = new BillDetailDeposit();
		billDetailDeposit.setRecordType(1);
		billDetailDeposit.setInUserId(userId);
		billDetailDeposit.setOutUserId(0);
		billDetailDeposit.setSpend(coinPrice.getCoinNumber());
		billDetailDeposit.setDiamond(0);
		billDetailDeposit.setRatio(0);
		billDetailDao.insertBillDetailDeposit(billDetailDeposit);
		UserWallet userWallet = new UserWallet();
		//更新用户钱包金币
		userWallet.setUserId(userId);
		userWallet.setDeposit(coinPrice.getCoinNumber());
		userWalletDao.reviseDeposit(userWallet);
		//更新用户能量
        energyLevelService.addUserEnergyLevel(userId, EnergyLevelType.ENERGY_TYPE_DEPOSIT,(int)coinPrice.getPrice());

        //邀请分成
		userInvitationIncomeDetailsHandler.incomeRechargeDetails(userId,
				new BigDecimal(Integer.toString(coinPrice.getCoinNumber())));
//		//用户统计v值
//		userCountDao.addVGradeSum(billDetail.getInUserId(), billDetail.getSpend());
//		//在线用户更新v值
//		Optional<Long> userOptional = lineTimeRedisDao.isExist(billDetail.getInUserId()+"");
//		if (userOptional.isPresent())
//			lineTimeRedisDao.CommonIncrementScore(billDetail.getInUserId()+"",billDetail.getSpend());
//		//排行榜统计
//		redisTemplateService.setVUserSort(billDetail.getInUserId(), billDetail.getSpend());
		// 发送广播通知
		systemMessageUtil.userRecharge(userId,coinPrice.getShowCoin(),coinPrice.getPrice());
		//充值用户使用系统账号发送给在线女主播
		//1.5.5 勿扰用户的充值消息，不向主播推送
		User user = userInfoDao.getUserInfoById(userId);
		if(user.getIsVideo() == 1){
			vestRobotMessageService.getSendMsgByHost(userId,coinPrice.getPrice()+"", EnumType.WALLET);
		}
		//1.5.5 首冲用户
		if(coinPrice.getCoinNumber() == 800 && !userRedisDao.isMemberFirstRechargeUser(userId)){
			userRedisDao.addFirstRechargeUser(userId);
		}
	}

	/**
	 *
	 * @param userId,用户id
	 * @param contentId,道具id
	 * @param contentType，1 金币，2：vip,3svip
	 */
	public void changeRechargeAmount(long userId, int contentId,int contentType) {
		UserWallet obj = new UserWallet();

		double price = 0.0;

		if(contentType==1){
			CoinPrice coinPrice = coinPriceService.getCoinPriceById(contentId);
			price=coinPrice.getPrice();
		}else if(contentType==2||contentType==3){
			Vip vip = vipService.getVipById(contentId);
			price = vip.getPrice();
		}
		obj.setUserId(userId);
		obj.setRechargeAmount(price);

		userWalletDao.updateRechargeAmount(obj);

	}

	public void changeRechargeAmount(long userId, double price) {
		UserWallet obj = new UserWallet();
		obj.setUserId(userId);
		obj.setRechargeAmount(price);

		userWalletDao.updateRechargeAmount(obj);

	}

    public int updateBeans(long userId, long beans) {
		return userWalletDao.updateBeans(userId,beans);
    }

    public int addBeans(long userId, long beans) {
		return userWalletDao.addBeans(userId,beans);
    }
}
